package com.sh.data.engine.domain.api.service.impl;

import cn.hutool.core.convert.Convert;
import com.alibaba.druid.sql.ast.statement.SQLSelectItem;
import com.alibaba.druid.util.JdbcConstants;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sh.data.engine.common.enumDefinition.DSType;
import com.sh.data.engine.common.enumDefinition.DataApiApproveStatusEnum;
import com.sh.data.engine.common.enumDefinition.DataApiStatusEnum;
import com.sh.data.engine.common.enumDefinition.DataApiTaskTypeEnum;
import com.sh.data.engine.common.exception.BusinessException;
import com.sh.data.engine.common.util.AESUtil;
import com.sh.data.engine.common.util.ServletUtils;
import com.sh.data.engine.domain.api.model.domain.*;
import com.sh.data.engine.domain.api.model.domain.rest.*;
import com.sh.data.engine.domain.api.model.param.*;
import com.sh.data.engine.domain.api.run.DataApiConfig;
import com.sh.data.engine.domain.api.run.DataApiTaskExecutor.RestResponseEntity;
import com.sh.data.engine.domain.api.service.DataApiAuthService;
import com.sh.data.engine.domain.api.service.DataApiRestService;
import com.sh.data.engine.domain.api.service.DataApiService;
import com.sh.data.engine.domain.api.util.DataApiUtil;
import com.sh.data.engine.domain.authority.service.TokenService;
import com.sh.data.engine.domain.base.model.UserContext;
import com.sh.data.engine.domain.base.model.enums.DirectoryMenuEnum;
import com.sh.data.engine.domain.common.service.DirectoryService;
import com.sh.data.engine.domain.integration.datasource.model.domain.DataSourceDetailDomain;
import com.sh.data.engine.domain.integration.datasource.service.DataSourceService;
import com.sh.data.engine.domain.normalization.index.model.domain.IndexCatalogDomain;
import com.sh.data.engine.domain.normalization.index.model.domain.IndexDomain;
import com.sh.data.engine.domain.normalization.index.service.IndexMgtService;
import com.sh.data.engine.domain.secret.service.SecretMgtService;
import com.sh.data.engine.domain.util.ConvertUtil;
import com.sh.data.engine.domain.util.LogUtil;
import com.sh.data.engine.domain.workspace.manager.model.domain.UserDomain;
import com.sh.data.engine.domain.workspace.manager.service.UserService;
import com.sh.data.engine.repository.dao.api.DataApiMapper;
import com.sh.data.engine.repository.dao.api.entity.DataApiAuthEntity;
import com.sh.data.engine.repository.dao.api.entity.DataApiEntity;
import com.sh.data.engine.repository.dao.api.entity.DataApiEntity.DataApiIndexEntity;
import com.sh.data.engine.repository.dao.api.entity.DataApiEntity.DataApiParamEntity;
import com.sh.data.engine.repository.dao.api.entity.DataApiEntity.DataApiRegisterEntity;
import com.sh.data.engine.repository.dao.common.entity.DirectoryEntity;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.Version;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.sh.data.engine.domain.api.service.DataApiRestService.SERVLETPATH;

/**
 * @author : fuchen
 * @date : 2022/1/19 16:42
 */
@Service
@Slf4j
public class DataApiServiceImpl extends ServiceImpl<DataApiMapper, DataApiEntity>
    implements DataApiService {

    @Autowired
    private DataApiConfig dataApiConfig;

    @Lazy
    @Autowired
    private DataApiAuthService dataApiAuthService;

    @Lazy
    @Autowired
    private DataSourceService dataSourceService;

    @Lazy
    @Autowired
    private DataApiRestService dataApiRestService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserService userService;

    @Autowired
    private DirectoryService directoryService;

    @Autowired
    private IndexMgtService indexMgtService;

    @Lazy
    @Autowired
    private SecretMgtService secretMgtService;

    @Autowired
    private TokenService tokenService;

    private static final int PUBLISHED_STATUS = 2;

    private String dataApiRedisKeyPrefix = "data_api_";

    @Override
    public boolean publishApiById(Long id) {
        DataApiEntity dataApiEntity = this.getById(id);
        if (dataApiEntity == null) {
            throw new BusinessException("api不存在");
        }
        if (dataApiEntity.getApiStatus().equals(DataApiStatusEnum.PUBLISHED.getStatus())) {
            throw new BusinessException("api 已发布");
        }
        dataApiEntity.setApiStatus(DataApiStatusEnum.PUBLISHED.getStatus());
        dataApiEntity.setPublishTime(new Date());

        this.updateById(dataApiEntity);
//        LogContext.put(LogKey.NAME.getKey(), dataApiEntity.getApiName());
        return true;
    }

    @Override
    public boolean publishApiByIds(List<Long> ids) {
        List<DataApiEntity> dataApiEntities = listByIds(ids);
        Map<Long, DataApiEntity> dataApiEntityMap = dataApiEntities.stream()
            .collect(Collectors.toMap(e -> e.getId(), e -> e));
        for (Long id : ids) {
            DataApiEntity dataApiEntity = dataApiEntityMap.get(id);
            if (Objects.nonNull(dataApiEntity)) {
                if (dataApiEntity.getApiStatus().equals(DataApiStatusEnum.PUBLISHED.getStatus())) {
                    continue;
                }
            }
            publishApiById(id);
        }
        return false;
    }

    @Override
    public boolean cancalPublishApiById(Long id) {
        DataApiEntity dataApiEntity = this.getById(id);
        if (dataApiEntity == null) {
            throw new BusinessException("api不存在");
        }
        if (!dataApiEntity.getApiStatus().equals(DataApiStatusEnum.PUBLISHED.getStatus())) {
            throw new BusinessException("api 未发布");
        }
        // 查询api是否被申请使用
        boolean r1 = dataApiAuthService.exitUsingApiByApiId(id);
        if (r1) {
            String format = String.format("api:[%s] 已经被使用，请撤销用户的使用再取消发布",
                dataApiEntity.getApiName());
            throw new BusinessException(format);
        }
        dataApiEntity.setApiStatus(DataApiStatusEnum.UN_PUBLISHED.getStatus());
        this.updateById(dataApiEntity);
//        LogContext.put(LogKey.NAME.getKey(), dataApiEntity.getApiName());
        return true;
    }

    @Override
    public String cancalPublishApiInfoById(Long id) {
        DataApiEntity dataApiEntity = this.getById(id);
        if (dataApiEntity == null) {
            throw new BusinessException("api不存在");
        }
        if (!dataApiEntity.getApiStatus().equals(DataApiStatusEnum.PUBLISHED.getStatus())) {
            throw new BusinessException("api 未发布");
        }
        // 查询api是否被申请使用
        boolean r1 = dataApiAuthService.exitUsingApiByApiId(id);
        if (r1) {
            return dataApiEntity.getApiName();
        }
        dataApiEntity.setApiStatus(DataApiStatusEnum.UN_PUBLISHED.getStatus());
        this.updateById(dataApiEntity);
//        LogContext.put(LogKey.NAME.getKey(), dataApiEntity.getApiName());
        return null;

    }

    @Override
    public boolean cancalPublishApiByIds(List<Long> ids) {
        List<DataApiEntity> dataApiEntities = listByIds(ids);
        Map<Long, DataApiEntity> dataApiEntityMap = dataApiEntities.stream()
            .collect(Collectors.toMap(e -> e.getId(), e -> e));
        boolean exitError = false;
        StringBuilder sb = new StringBuilder();
        sb.append("无法取消以下已经被使用的数据服务:“");
        sb.append("\n");
        for (Long id : ids) {
            DataApiEntity dataApiEntity = dataApiEntityMap.get(id);
            if (Objects.nonNull(dataApiEntity)) {
                if (dataApiEntity.getApiStatus().equals(DataApiStatusEnum.UN_PUBLISHED.getStatus())) {
                    continue;
                }
            }
            String s = cancalPublishApiInfoById(id);
            if (StringUtils.isNotBlank(s)) {
                exitError = true;
                sb.append("\n");
                sb.append(s);
                sb.append("   ");
            }
        }
        if (exitError) {
            sb.append("”请撤销用户的使用再取消发布");
            throw new BusinessException(sb.toString());
        }
        return true;
    }

    //    @BizDataIndexAnnotation(
//        type = BizDataIndexTypeEnum.DATA_SERVICE,
//        dataIdFieldName = "id",
//        dataIdParamIndex = 0,
//        operateType = BizDataIndexAnnotation.OperateType.SAVE)
    @Override
    public boolean saveApi(DataApiBaseParam dataApiBaseParam) {
        Long id = dataApiBaseParam.getId();

        DataApiEntity dataApiEntity = new DataApiEntity();
        Integer apiType = dataApiBaseParam.getApiType();
        DataApiTaskTypeEnum dataApiTaskTypeEnum = DataApiTaskTypeEnum.getTaskTypeByCode(apiType);
        switch (dataApiTaskTypeEnum) {
            case SCRIPT:
                dataApiEntity = this.parseScriptDataApiInfo(dataApiBaseParam);
                break;
            case GUIDE:
                dataApiEntity = this.parseGuideDataApiInfo(dataApiBaseParam);
                break;
            case INDEXLIB:
                dataApiEntity = this.parseIndexLibDataApiInfo(dataApiBaseParam);
            default:
                break;
        }
        boolean flag = false;
        // 判断名称是否变更，同步到auth表
        if (Objects.nonNull(id)) {
            DataApiEntity byId = this.getById(id);
            if (!byId.getApiName().equals(dataApiBaseParam.getApiName())) {
                flag = true;
            }
        }

        // 判断API path是否已经存在，如果选择的是user
        String apiPath = dataApiBaseParam.getApiPath();
        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>().eq(DataApiEntity::getApiPath, apiPath);
        if (Objects.nonNull(dataApiBaseParam.getId())) {
            eq.ne(DataApiEntity::getId, dataApiBaseParam.getId());
        }
        Integer authType = dataApiBaseParam.getAuthType();
        if (Objects.isNull(authType) || authType.equals(0)) {
            eq.eq(DataApiEntity::getProjectId, dataApiBaseParam.getProjectId());
        }
        long count = this.count(eq);
        if (count > 0) {
            throw new BusinessException(String.format("API路径[%s]已存在", apiPath));
        }

        LambdaQueryWrapper<DataApiEntity> ne =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, dataApiBaseParam.getProjectId())
                .eq(DataApiEntity::getApiName, dataApiBaseParam.getApiName())
                .ne(
                    Objects.nonNull(dataApiBaseParam.getId()),
                    DataApiEntity::getId,
                    dataApiBaseParam.getId());

        long count2 = this.count(ne);
        if (count2 > 0) {
            throw new BusinessException(
                String.format("API名称[%s]已存在", dataApiBaseParam.getApiName()));
        }

        DataApiExampleTestParam dataApiExampleTestParam = new DataApiExampleTestParam();
        dataApiExampleTestParam.setPageable(dataApiBaseParam.getPageable());
        dataApiExampleTestParam.setDataApiParamParams(dataApiBaseParam.getOutputParamList());
        String responseExample = this.getResponseExample(dataApiExampleTestParam);
        dataApiEntity.setApiStatus(DataApiStatusEnum.UN_PUBLISHED.getStatus());
        dataApiEntity.setResponseExample(responseExample);
        // if id not empty ,update selective
        if (Objects.isNull(id)) {
            dataApiEntity.setFailCount(0L);
            dataApiEntity.setTotalCount(0L);
            dataApiEntity.setSuccessCount(0L);
            dataApiEntity.setApiParamEntity();
            this.save(dataApiEntity);
            dataApiBaseParam.setId(dataApiEntity.getId());
//            LogContext.put(LogKey.NAME.getKey(), dataApiBaseParam.getApiName());
        } else {
            dataApiEntity.setApiParamEntity();
            this.updateById(dataApiEntity);
//            LogContext.put(LogKey.NAME.getKey(), dataApiBaseParam.getApiName());
//            LogContext.put(LogKey.ISUPDATE.getKey(), LogKey.ISUPDATE.getValue());
        }
//        LogContext.put(LogKey.NAME.getKey(), dataApiEntity.getApiName());
        // 变更到auth表
        if (flag) {
//            LogContext.put(LogKey.ISUPDATE.getKey(), LogKey.ISUPDATE.getValue());
            dataApiAuthService.updateApiAuthName(id, dataApiBaseParam.getApiName());
        }

        return true;
    }

    @Override
    public boolean saveRegisterApi(DataApiRegisterParam dataApiRegisterParam) {

        DataApiRegisterEntity convert =
            Convert.convert(DataApiRegisterEntity.class, dataApiRegisterParam);

        String apiPath = dataApiRegisterParam.getApiPath();

        LambdaQueryWrapper<DataApiEntity> ne2 =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, dataApiRegisterParam.getProjectId())
                .eq(DataApiEntity::getApiPath, apiPath)
                .ne(DataApiEntity::getId, dataApiRegisterParam.getId());

        long count = this.count(ne2);
        if (count > 0) {
            throw new BusinessException(String.format("API路径[%s]已存在", apiPath));
        }

        LambdaQueryWrapper<DataApiEntity> ne3 =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, dataApiRegisterParam.getProjectId())
                .eq(DataApiEntity::getApiName, dataApiRegisterParam.getApiName())
                .ne(DataApiEntity::getId, dataApiRegisterParam.getId());

        long count2 = this.count(ne3);
        if (count2 > 0) {
            throw new BusinessException(
                String.format("API名称[%s]已存在", dataApiRegisterParam.getApiName()));
        }

        boolean flag = false;
        // 判断名称是否变更，同步到auth表
        if (Objects.nonNull(dataApiRegisterParam.getId())) {
            DataApiEntity byId = this.getById(dataApiRegisterParam.getId());
            if (!byId.getApiName().equals(dataApiRegisterParam.getApiName())) {
                flag = true;
            }
        }

        Long id = dataApiRegisterParam.getId();

        // 编辑
        DataApiRegisterEntity dataApiRegisterEntity = new DataApiRegisterEntity();
        dataApiRegisterEntity.setUrl(dataApiRegisterParam.getUrl());
        dataApiRegisterEntity.setHttpRequestMethod(dataApiRegisterParam.getHttpRequestMethod());
        if (Objects.nonNull(id)) {
            DataApiEntity dataApiEntity = this.getById(id);
            DataApiEntity dataApiEntity1 =
                ConvertUtil.copyProperties(dataApiRegisterParam, DataApiEntity.class);
            dataApiEntity1.setApiStatus(DataApiStatusEnum.UN_PUBLISHED.getStatus());
            dataApiEntity1.setDataApiRegister(convert);
            dataApiEntity1.setUpdateTime(new Date());
            dataApiEntity1.setDataApiRegister(dataApiRegisterEntity);
            dataApiEntity1.setFailCount(dataApiEntity.getFailCount());
            dataApiEntity1.setTotalCount(dataApiEntity.getTotalCount());
            dataApiEntity1.setSuccessCount(dataApiEntity.getSuccessCount());
            dataApiEntity1.setCreateTime(dataApiEntity.getCreateTime());
            dataApiEntity1.setCreatorId(dataApiEntity.getCreatorId());
            dataApiEntity1.setUpdaterId(dataApiEntity.getUpdaterId());
            this.updateById(dataApiEntity1);
        } else {
            DataApiEntity dataApiEntity =
                ConvertUtil.copyProperties(dataApiRegisterParam, DataApiEntity.class);
            dataApiEntity.setDataApiRegister(convert);
            dataApiEntity.setFailCount(0L);
            dataApiEntity.setTotalCount(0L);
            dataApiEntity.setSuccessCount(0L);
            dataApiEntity.setDataApiRegister(dataApiRegisterEntity);
            dataApiEntity.setApiStatus(DataApiStatusEnum.UN_PUBLISHED.getStatus());
            this.save(dataApiEntity);
        }
        return true;
    }

    private DataApiEntity parseIndexLibDataApiInfo(DataApiBaseParam dataApiBaseParam) {

        DataApiIndexParam dataApiIndexParam = (DataApiIndexParam) dataApiBaseParam;
        DataApiEntity dataApiEntity =
            ConvertUtil.copyProperties(dataApiIndexParam, DataApiEntity.class);

        List<DataApiParamParam> allParamRequest = Lists.newArrayList();
        List<DataApiParamParam> inputParamRequest = dataApiIndexParam.getInputParamList();
        List<DataApiParamParam> outputParamRequest = dataApiIndexParam.getOutputParamList();

        if (Objects.nonNull(inputParamRequest)) {
            allParamRequest.addAll(inputParamRequest);
        }
        if (Objects.nonNull(outputParamRequest)) {
            allParamRequest.addAll(outputParamRequest);
        }
        List<DataApiParamEntity> dataApiParamEntities =
            ConvertUtil.copyProperties(allParamRequest, DataApiParamEntity.class);
        DataApiIndexEntity dataApiIndexEntity = new DataApiIndexEntity();
        dataApiIndexEntity.setIndexId(dataApiIndexParam.getIndexId());
        dataApiIndexEntity.setDirId(dataApiIndexParam.getDirId());
        dataApiEntity.setApiParamEntityList(dataApiParamEntities);
        dataApiEntity.setCreateTime(new Date());
        dataApiEntity.setCreatorId(dataApiBaseParam.getUserId());
        dataApiEntity.setUpdateTime(new Date());

        dataApiEntity.setDataApiIndex(dataApiIndexEntity);
        return dataApiEntity;
    }

    private DataApiEntity parseGuideDataApiInfo(DataApiBaseParam dataApiBaseParam) {
        DataApiGuideParam dataApiGuideParam = (DataApiGuideParam) dataApiBaseParam;
        DataApiEntity dataApiEntity =
            ConvertUtil.copyProperties(dataApiGuideParam, DataApiEntity.class);
        List<DataApiParamParam> allParamRequest = Lists.newArrayList();
        List<DataApiParamParam> inputParamRequest = dataApiGuideParam.getInputParamList();
        List<DataApiParamParam> outputParamRequest = dataApiGuideParam.getOutputParamList();
        if (Objects.nonNull(inputParamRequest)) {
            allParamRequest.addAll(inputParamRequest);
        }
        if (Objects.nonNull(outputParamRequest)) {
            allParamRequest.addAll(outputParamRequest);
        }
        List<DataApiParamEntity> dataApiParamEntities =
            ConvertUtil.copyProperties(allParamRequest, DataApiParamEntity.class);
        dataApiEntity.setApiParamEntityList(dataApiParamEntities);
        return dataApiEntity;
    }

    private DataApiEntity parseScriptDataApiInfo(DataApiBaseParam dataApiBaseParam) {
        DataApiScriptParam dataApiScriptParam = (DataApiScriptParam) dataApiBaseParam;
        DataApiEntity dataApiEntity =
            ConvertUtil.copyProperties(dataApiScriptParam, DataApiEntity.class);
        List<DataApiParamParam> allParamRequest = Lists.newArrayList();
        List<DataApiParamParam> inputParamRequest = dataApiScriptParam.getInputParamList();
        List<DataApiParamParam> outputParamRequest = dataApiScriptParam.getOutputParamList();

        if (Objects.nonNull(inputParamRequest)) {
            allParamRequest.addAll(inputParamRequest);
        }
        if (Objects.nonNull(outputParamRequest)) {
            allParamRequest.addAll(outputParamRequest);
        }
        List<DataApiParamEntity> dataApiParamEntities =
            ConvertUtil.copyProperties(allParamRequest, DataApiParamEntity.class);
        dataApiEntity.setApiParamEntityList(dataApiParamEntities);
        dataApiEntity.setCreateTime(new Date());
        dataApiEntity.setCreatorId(dataApiBaseParam.getUserId());
        dataApiEntity.setUpdateTime(new Date());
        return dataApiEntity;
    }

    @Override
    public Map<Long, DataApiEntity> getApiPathMap(List<Long> ids) {

        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        List<DataApiEntity> dataApiEntities = this.listByIds(ids);
        Map<Long, DataApiEntity> collect =
            dataApiEntities.stream().collect(Collectors.toMap(e -> e.getId(), e -> e));
        return collect;
    }

    @Override
    public DataApiDomain findDataApiById(Long id) {
        DataApiEntity byId = this.getById(id);
        DataApiDomain dataApiDomain = Convert.convert(DataApiDomain.class, byId);
        return dataApiDomain;
    }

    @Override
    public IPage<DataApiMyApiDomain> findMyDataApiListByIds(
        DataApiMyApiParam dataApiMyApiParam, String username, List<Long> ids) {

        if (CollectionUtils.isEmpty(ids)) {
            return new Page<>();
        }

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, dataApiMyApiParam.getProjectId())
                .eq(DataApiEntity::getCreatorId, dataApiMyApiParam.getUserId());

        eq.in(DataApiEntity::getId, ids);

        eq.like(
            StringUtils.isNotBlank(dataApiMyApiParam.getApiName()),
            DataApiEntity::getApiName,
            dataApiMyApiParam.getApiName());

        eq.eq(
            Objects.nonNull(dataApiMyApiParam.getApiStatus()),
            DataApiEntity::getApiStatus,
            dataApiMyApiParam.getApiStatus());

        eq.orderByDesc(DataApiEntity::getUpdateTime);

        IPage<DataApiMyApiDomain> dataApiDomainPageResult =
            page(new Page<>(dataApiMyApiParam.getPageNum(), dataApiMyApiParam.getPageSize()), eq)
                .convert(e -> Convert.convert(DataApiMyApiDomain.class, e));

        List<DataApiMyApiDomain> result = dataApiDomainPageResult.getRecords();
        for (DataApiMyApiDomain domain : result) {
            domain.setUsername(username);
        }
        return dataApiDomainPageResult;
    }

    @Override
    public IPage<DataApiMyApiDomain> findMyDataApiList(
        DataApiMyApiParam dataApiMyApiParam, String username, List<Long> groupIds) {

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, dataApiMyApiParam.getProjectId())
                .eq(DataApiEntity::getCreatorId, dataApiMyApiParam.getUserId());

        if (StringUtils.isNotBlank(dataApiMyApiParam.getApiName())) {
            eq.and(
                wrapper -> wrapper
                    .like(DataApiEntity::getApiName, dataApiMyApiParam.getApiName())
                    .or()
                    .like(DataApiEntity::getApiPath, dataApiMyApiParam.getApiName())
            );
        }
        if (Objects.nonNull(dataApiMyApiParam.getApiStatus())) {
            eq.eq(DataApiEntity::getApiStatus, dataApiMyApiParam.getApiStatus());
        }
        if (CollectionUtils.isNotEmpty(groupIds)) {
            eq.in(DataApiEntity::getApiGroupId, groupIds);
        }

        eq.orderByAsc(DataApiEntity::getApiStatus);
        eq.orderByDesc(DataApiEntity::getUpdateTime);
        IPage<DataApiMyApiDomain> dataApiDomainPageResult =
            page(new Page<>(dataApiMyApiParam.getPageNum(), dataApiMyApiParam.getPageSize()), eq)
                .convert(e -> Convert.convert(DataApiMyApiDomain.class, e));

        List<DataApiMyApiDomain> result = dataApiDomainPageResult.getRecords();
        for (DataApiMyApiDomain domain : result) {
            domain.setUsername(username);
        }
        return dataApiDomainPageResult;
    }

    //    @BizDataIndexAnnotation(
//        type = BizDataIndexTypeEnum.DATA_SERVICE,
//        dataIdFieldName = "id",
//        dataIdParamIndex = 0,
//        operateType = OperateType.DELETE)
    @Override
    public boolean removeDataApiById(Long id) {

        // 判断该api状态是否能删除
        DataApiEntity dataApiEntity = this.getById(id);
        if (dataApiEntity.getApiStatus().equals(PUBLISHED_STATUS)) {
            throw new BusinessException("该api已发布,不能被删除");
        }
        dataApiAuthService.removeDataApiAuthByApiId(id);
        this.removeById(id);
//        LogContext.put(LogKey.NAME.getKey(), dataApiEntity.getApiName());
        return true;
    }

    @Override
    public DataApiConfigInfoDomain getDataApiConfig(Long id) {

        if (id == null) {
            return null;
        }
        DataApiEntity dataApiEntity = this.getById(id);
        DataApiDomain dataApiDomain = Convert.convert(DataApiDomain.class, dataApiEntity);

        List<DataApiParamEntity> apiParamEntityList = dataApiEntity.getApiParamEntityList();
        DataApiConfigInfoDomain dataApiConfigInfoDomain =
            ConvertUtil.copyProperties(dataApiDomain, DataApiConfigInfoDomain.class);

        DataApiRegisterEntity dataApiRegister = dataApiEntity.getDataApiRegister();
        if (null != dataApiRegister) {
            DataApiRegisterDomain convert = Convert.convert(DataApiRegisterDomain.class, dataApiRegister);
            dataApiDomain.setApiRegisterDomain(convert);
        }

        if (CollectionUtils.isNotEmpty(apiParamEntityList)) {
            List<DataApiTaskParamDomain> dataApiTaskParamDomains =
                ConvertUtil.copyProperties(apiParamEntityList, DataApiTaskParamDomain.class);
            dataApiConfigInfoDomain.setApiParamEntityList(dataApiTaskParamDomains);
        }

        DataApiConfigInfoDomain dataApiConfigInfoByType =
            this.getDataApiConfigInfoByType(dataApiConfigInfoDomain, dataApiDomain);
        return dataApiConfigInfoByType;
    }

    @Override
    public DataApiConfigInfoDomain getDataApiConfigInfoByType(
        DataApiConfigInfoDomain taskConfigInfo, DataApiDomain dataApiDomain) {

        Integer apiType = dataApiDomain.getApiType();
        DataApiTaskTypeEnum taskTypeEnum = DataApiTaskTypeEnum.getTaskTypeByCode(apiType);

        switch (taskTypeEnum) {
            case SCRIPT:
                taskConfigInfo = this.getScriptTaskConfigInfo(dataApiDomain, taskConfigInfo);
                break;
            case REGIEST:
                taskConfigInfo = this.getRegisterTaskConfigInfo(dataApiDomain, taskConfigInfo);
                break;
            case GUIDE:
                taskConfigInfo = this.getGuideTaskConfigInfo(dataApiDomain, taskConfigInfo);
                break;
            case INDEXLIB:
                taskConfigInfo = this.getIndexTaskConfigInfo(dataApiDomain, taskConfigInfo);
        }
        return taskConfigInfo;
    }

    private DataApiConfigInfoDomain getIndexTaskConfigInfo(
        DataApiDomain dataApiDomain, DataApiConfigInfoDomain taskConfigInfo) {

        DataSourceDetailDomain dataSourceDetailById =
            dataSourceService.getDataSourceDetailByProjectId(dataApiDomain.getProjectId(), false);
        if (Objects.isNull(dataSourceDetailById)) {
            return null;
        }
        DataApiIndexTaskConfigInfoDomain dataApiIndexTaskConfigInfoDomain =
            ConvertUtil.copyProperties(taskConfigInfo, DataApiIndexTaskConfigInfoDomain.class);

        dataApiIndexTaskConfigInfoDomain.setTableName(dataApiDomain.getTableName());
        boolean hasSchema = DSType.hasSchema(dataSourceDetailById.getDsType());
        String tableName = dataApiDomain.getTableName();
        if (hasSchema && tableName.contains(".")) {
            String[] names = tableName.split("\\.", 2);
            tableName = "\"" + names[0] + "\"" + ".\"" + names[1] + "\"";
            if (DSType.SQLServer.name().equals(dataSourceDetailById.getDsType())) {
                tableName = names[0] + ".[" + names[1] + "]";
            }
            dataApiIndexTaskConfigInfoDomain.setTableName(tableName);
        }

        List<DataApiTaskParamDomain> apiParamEntityList =
            dataApiIndexTaskConfigInfoDomain.getApiParamEntityList();

        List<DataApiTaskParamDomain> collect =
            apiParamEntityList.stream()
                .filter(e -> StringUtils.isNotBlank(e.getBindColumnName()))
                .collect(Collectors.toList());

        if (DSType.Oracle.name().equals(dataSourceDetailById.getDsType())
            || DSType.Sap.name().equals(dataSourceDetailById.getDsType())) {
            collect.stream()
                .forEach(
                    e -> {
                        String bindColumnName = e.getBindColumnName();
                        e.setBindColumnName("\"" + bindColumnName + "\"");
                    });
        }

        dataApiIndexTaskConfigInfoDomain.setApiParamEntityList(collect);

        dataApiIndexTaskConfigInfoDomain.setDatasourceId(dataSourceDetailById.getId());
        dataApiIndexTaskConfigInfoDomain.setDsType(dataSourceDetailById.getDsType());
        dataApiIndexTaskConfigInfoDomain.setUsername(dataSourceDetailById.getUsername());
        dataApiIndexTaskConfigInfoDomain.setPassword(dataSourceDetailById.getPassword());
        dataApiIndexTaskConfigInfoDomain.setDsLink(dataSourceDetailById.getDsLink());
        dataApiIndexTaskConfigInfoDomain.setIsSecurity(dataApiDomain.getIsSecurity());
        return dataApiIndexTaskConfigInfoDomain;
    }

    private DataApiConfigInfoDomain getGuideTaskConfigInfo(
        DataApiDomain dataApiDomain, DataApiConfigInfoDomain taskConfigInfo) {
        Long datasourceId = dataApiDomain.getDatasourceId();
        DataSourceDetailDomain dataSourceDetailById =
            dataSourceService.getDataSourceDetailById(datasourceId, false);
        if (Objects.isNull(dataSourceDetailById)) {
            return null;
        }
        DataApiGuideTaskConfigInfoDomain dataApiGuideTaskConfigInfoDomain =
            ConvertUtil.copyProperties(taskConfigInfo, DataApiGuideTaskConfigInfoDomain.class);
        dataApiGuideTaskConfigInfoDomain.setTableName(dataApiDomain.getTableName());
        boolean hasSchema = DSType.hasSchema(dataSourceDetailById.getDsType());
        String tableName = dataApiDomain.getTableName();
        if (hasSchema && tableName.contains(".")) {
            String[] names = tableName.split("\\.", 2);
            tableName = "\"" + names[0] + "\"" + ".\"" + names[1] + "\"";
            if (DSType.SQLServer.name().equals(dataSourceDetailById.getDsType())) {
                tableName = names[0] + ".[" + names[1] + "]";
            }
            dataApiGuideTaskConfigInfoDomain.setTableName(tableName);
        }

        List<DataApiTaskParamDomain> apiParamEntityList =
            dataApiGuideTaskConfigInfoDomain.getApiParamEntityList();

        List<DataApiTaskParamDomain> collect =
            apiParamEntityList.stream()
                .filter(e -> StringUtils.isNotBlank(e.getBindColumnName()))
                .collect(Collectors.toList());

        if (DSType.Oracle.name().equals(dataSourceDetailById.getDsType())
            || DSType.Sap.name().equals(dataSourceDetailById.getDsType())) {
            collect.stream()
                .forEach(
                    e -> {
                        String bindColumnName = e.getBindColumnName();
                        e.setBindColumnName("\"" + bindColumnName + "\"");
                    });
        }

        dataApiGuideTaskConfigInfoDomain.setApiParamEntityList(collect);
        dataApiGuideTaskConfigInfoDomain.setDatasourceId(dataApiDomain.getDatasourceId());
        dataApiGuideTaskConfigInfoDomain.setDsType(dataSourceDetailById.getDsType());

        dataApiGuideTaskConfigInfoDomain.setUsername(dataSourceDetailById.getUsername());
        dataApiGuideTaskConfigInfoDomain.setPassword(dataSourceDetailById.getPassword());
        dataApiGuideTaskConfigInfoDomain.setDsLink(dataSourceDetailById.getDsLink());
        dataApiGuideTaskConfigInfoDomain.setIsSecurity(dataApiDomain.getIsSecurity());

        return dataApiGuideTaskConfigInfoDomain;
    }

    private DataApiConfigInfoDomain getRegisterTaskConfigInfo(
        DataApiDomain dataApiDomain, DataApiConfigInfoDomain taskConfigInfo) {

        DataApiRegisterTaskConfigInfoDomain registerTaskConfigInfoDomain =
            ConvertUtil.copyProperties(taskConfigInfo, DataApiRegisterTaskConfigInfoDomain.class);

        DataApiRegisterDomain dataApiRegisterDomain = dataApiDomain.getApiRegisterDomain();

        if (Objects.isNull(dataApiRegisterDomain)) {
            return null;
        }
        registerTaskConfigInfoDomain.setUrl(dataApiRegisterDomain.getUrl());
        registerTaskConfigInfoDomain.setApiHttpRequestHeaderDomain(
            dataApiRegisterDomain.getApiHttpRequestHeader());
        registerTaskConfigInfoDomain.setHttpRequestMethod(dataApiRegisterDomain.getHttpRequestMethod());
        registerTaskConfigInfoDomain.setApiHttpRequestBodyDomain(
            dataApiRegisterDomain.getApiHttpRequestBody());
        registerTaskConfigInfoDomain.setApiHttpAuthDomain(dataApiRegisterDomain.getApiHttpAuth());
        registerTaskConfigInfoDomain.setIsSecurity(dataApiDomain.getIsSecurity());
        return registerTaskConfigInfoDomain;
    }

    private DataApiConfigInfoDomain getScriptTaskConfigInfo(
        DataApiDomain dataApiDomain, DataApiConfigInfoDomain taskConfigInfo) {
        DataApiScriptTaskConfigInfoDomain scriptTaskConfigInfoDomain =
            ConvertUtil.copyProperties(taskConfigInfo, DataApiScriptTaskConfigInfoDomain.class);
        scriptTaskConfigInfoDomain.setApiScript(dataApiDomain.getApiScript());
        DataSourceDetailDomain dataSourceDetailById =
            dataSourceService.getDataSourceDetailById(dataApiDomain.getDatasourceId(), false);

        List<DataApiTaskParamDomain> apiParamEntityList =
            scriptTaskConfigInfoDomain.getApiParamEntityList();

        List<DataApiTaskParamDomain> collect =
            apiParamEntityList.stream()
                .filter(
                    e ->
                        (StringUtils.isNotBlank(e.getBindColumnName()) && e.getParamType() == 1)
                            || e.getParamType() == 0)
                .collect(Collectors.toList());

        if (DSType.Sap.name().equals(dataSourceDetailById.getDsType())) {
            collect.stream()
                .forEach(
                    e -> {
                        String bindColumnName = e.getBindColumnName();
                        e.setBindColumnName("\"" + bindColumnName + "\"");
                    });
        }

        scriptTaskConfigInfoDomain.setApiParamEntityList(collect);

        String dsLink = dataSourceDetailById.getDsLink();
        if (DSType.IoTDB.name().equals(dataSourceDetailById.getDsType()) && dsLink.indexOf(",") != -1) {
            dsLink = dsLink.split(",")[0];
        }
        scriptTaskConfigInfoDomain.setDsLink(dsLink);
        scriptTaskConfigInfoDomain.setDsType(dataSourceDetailById.getDsType());
        scriptTaskConfigInfoDomain.setPassword(dataSourceDetailById.getPassword());
        scriptTaskConfigInfoDomain.setUsername(dataSourceDetailById.getUsername());

        if (DSType.InfluxDB.name().equals(dataSourceDetailById.getDsType())) {
            scriptTaskConfigInfoDomain.setDbName(dataSourceDetailById.getDbName());
            scriptTaskConfigInfoDomain.setSchema(dataSourceDetailById.getRdbmsConfig().getSchema());
        }

        scriptTaskConfigInfoDomain.setIsSecurity(dataApiDomain.getIsSecurity());

        return scriptTaskConfigInfoDomain;
    }

    @Override
    public DataApiDomain getDataApiDetailById(Long id) {
        String userId = UserContext.getUserId();
        DataApiEntity dataApiEntity = this.getById(id);
        DataApiDomain dataApiDomain = ConvertUtil.copyProperties(dataApiEntity, DataApiDomain.class);
        List<DataApiParamEntity> apiParamEntityList = dataApiEntity.getApiParamEntityList();
        DataApiRegisterEntity dataApiRegisterEntity = dataApiEntity.getDataApiRegister();

        if (CollectionUtils.isNotEmpty(apiParamEntityList)) {
            List<DataApiTaskParamDomain> apiParamDomains =
                ConvertUtil.copyProperties(apiParamEntityList, DataApiTaskParamDomain.class);
            dataApiDomain.setApiParamEntityList(apiParamDomains);
        }

        if (Objects.nonNull(dataApiRegisterEntity)) {
            DataApiRegisterDomain dataApiRegisterDomain =
                Convert.convert(DataApiRegisterDomain.class, dataApiRegisterEntity);
            dataApiDomain.setApiRegisterDomain(dataApiRegisterDomain);
        }

        Long apiGroupId = dataApiEntity.getApiGroupId();
        DirectoryEntity directoryEntityById = directoryService.getDirectoryEntityById(apiGroupId);
        if (Objects.nonNull(directoryEntityById)) {
            dataApiDomain.setApiGroup(directoryEntityById.getDirName());
        }

        Integer apiType = dataApiEntity.getApiType();
        Integer authType = dataApiEntity.getAuthType();
        Integer isSecurity = dataApiEntity.getIsSecurity();
        if (DataApiTaskTypeEnum.INDEXLIB.getTypeCode().equals(apiType)) {
            DataApiIndexEntity dataApiIndex = dataApiEntity.getDataApiIndex();
            if (null != dataApiIndex) {
                Long indexId = dataApiIndex.getIndexId();
                Long dirId = dataApiIndex.getDirId();
                IndexDomain indexDomain = indexMgtService.indexDetail(indexId);
                if (null == indexDomain) {
                    throw new BusinessException("指标被下架或已删除");
                }
                IndexCatalogDomain indexCatalogById = indexMgtService.getIndexCatalogById(dirId);
                if (null != indexCatalogById) {
                    dataApiDomain.setIndexGroup(indexCatalogById.getName());
                }
                dataApiDomain.setIndexId(indexId);
                dataApiDomain.setIndexName(indexDomain.getName());
                dataApiDomain.setDirId(dirId);
            }
        }
        // token 设置

        String testToken =
            this.getTestApiToken(
                dataApiDomain.getId(),
                authType,
                dataApiDomain.getApiPath(),
                isSecurity);
        String prodToken = "";

        if (dataApiDomain.getApiStatus().equals(1)) {
            DataApiAuthDomain dataApiAuthDomain =
                dataApiAuthService.findAuthDomainByUserIdAndApiId(userId, dataApiEntity.getId());
            if (Objects.nonNull(dataApiAuthDomain)
                && dataApiAuthDomain
                .getApproveStatus()
                .equals(DataApiApproveStatusEnum.PASSED.getApproveStatus())) {
                prodToken = dataApiAuthDomain.getApiToken();
                if (Objects.nonNull(dataApiDomain.getAuthType()) && dataApiDomain.getAuthType().equals(1)) {
                    UserDomain userEntity = userService.getUserById(userId);
                    prodToken = tokenService.getToken(userEntity.getId());
                }
                String apiFullPath =
                    this.getApiFullPath(dataApiDomain.getApiPath(), prodToken, dataApiDomain.getAuthType(),
                        isSecurity);
                dataApiDomain.setProdApiUrl(apiFullPath);
            }
        }
        String apiTestPath =
            this.getApiFullPath(dataApiDomain.getApiPath(), testToken, dataApiDomain.getAuthType(),
                isSecurity);
        dataApiDomain.setTestApiUrl(apiTestPath);
        if (Objects.nonNull(dataApiEntity.getDatasourceId())) {
            DataSourceDetailDomain dataSourceDetailById =
                dataSourceService.getDataSourceDetailById(dataApiEntity.getDatasourceId(), true);
            dataApiDomain.setDatasourceName(dataSourceDetailById.getDsName());
            StringBuilder builder = new StringBuilder();
            if (StringUtils.isBlank(dataSourceDetailById.getDbName())) {
                if (Objects.nonNull(dataSourceDetailById.getRdbmsConfig())
                    && StringUtils.isNotBlank(dataSourceDetailById.getRdbmsConfig().getSchema())) {
                    builder.append(dataSourceDetailById.getRdbmsConfig().getSchema());
                }
            } else {
                builder.append(dataSourceDetailById.getDbName());
            }
            String s = builder.append("-").append(dataApiEntity.getTableName()).toString();
            dataApiDomain.setDatasourceInfo(s);
        }
        return dataApiDomain;
    }

    @Override
    public IPage<DataApiBaseDomain> getMarketApiList(
        Long projectId,
        List<Long> groupId,
        String apiName,
        Integer pageNum,
        Integer pageSize,
        String userId) {

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, projectId)
                .eq(DataApiEntity::getApiStatus, DataApiStatusEnum.PUBLISHED.getStatus());

        if (CollectionUtils.isNotEmpty(groupId)) {
            eq.in(DataApiEntity::getApiGroupId, groupId);
        }
        if (StringUtils.isNotBlank(apiName)) {
            eq.and(
                wrapper -> wrapper
                    .like(DataApiEntity::getApiName, apiName)
                    .or()
                    .like(DataApiEntity::getApiPath, apiName)
            );
        }

        eq.orderByDesc(DataApiEntity::getUpdateTime);
        eq.orderByAsc(DataApiEntity::getApiStatus);
        IPage<DataApiBaseDomain> dataApiBaseDomainPageResult =
            page(new Page<>(pageNum, pageSize), eq)
                .convert(e -> Convert.convert(DataApiBaseDomain.class, e));

        List<DataApiBaseDomain> result = dataApiBaseDomainPageResult.getRecords();
        result.forEach(
            e -> {
                DataApiAuthDomain authDomainByUserIdAndApiId =
                    dataApiAuthService.findAuthDomainByUserIdAndApiId(userId, e.getId());
                if (null != authDomainByUserIdAndApiId) {
                    e.setApproveStatus(authDomainByUserIdAndApiId.getApproveStatus());
                }
                String creatorId = e.getCreatorId();
                UserDomain userById = userService.getUserById(creatorId);
                if (Objects.isNull(userById)) {
                    e.setUsername("匿名用户");
                } else {
                    e.setUsername(userById.getUserName());
                }
            });

        return dataApiBaseDomainPageResult;
    }

    @Override
    public List<DataApiEntity> getAllPublishedApiList(Long projectId) {
        List<DataApiEntity> list =
            this.list(
                new LambdaQueryWrapper<DataApiEntity>()
                    .eq(DataApiEntity::getProjectId, projectId)
                    .eq(DataApiEntity::getApiStatus, DataApiStatusEnum.PUBLISHED.getStatus()));
        List<Long> apiIds = list.stream().map(e -> e.getId()).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(apiIds)) {
            List<DataApiAuthEntity> authEntities =
                dataApiAuthService.list(
                    new LambdaQueryWrapper<DataApiAuthEntity>()
                        .in(DataApiAuthEntity::getApiId, apiIds)
                        .eq(
                            DataApiAuthEntity::getApproveStatus,
                            DataApiApproveStatusEnum.PASSED.getApproveStatus()));
            List<Long> ids = authEntities.stream().map(e -> e.getApiId()).collect(Collectors.toList());
            if (CollectionUtils.isNotEmpty(ids)) {
                return this.listByIds(ids);
            }
        }
        return null;
    }

    @Override
    public List<DataApiBaseDomain> getApiList(Long projectId, Long dirId) {
        List<Long> ids = Lists.newArrayList();
        // dirId为0，查询全部任务，不要很根据dirId以及下面的子级目录id去查，会导致没有定义目录的任务无法展示
        if (!"0".equals(dirId)) {
            List<DirectoryEntity> childrenById =
                directoryService.getChildrenById(dirId, projectId, DirectoryMenuEnum.OFFLINE);
            ids = childrenById.stream().map(DirectoryEntity::getId).collect(Collectors.toList());
            ids.add(dirId);
        }
        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, projectId)
                .eq(DataApiEntity::getApiStatus, DataApiStatusEnum.PUBLISHED.getStatus())
                .in(DataApiEntity::getApiGroupId, ids);
        eq.orderByDesc(DataApiEntity::getUpdateTime);
        List<DataApiEntity> list = this.list(eq);
        List<String> collect = list.stream().map(e -> e.getCreatorId()).collect(Collectors.toList());
        Map<String, String> mapByUserIds = userService.getMapByUserIds(collect);
        List<DataApiBaseDomain> dataApiBaseDomains = Convert.toList(DataApiBaseDomain.class, collect);
        dataApiBaseDomains.forEach(
            e -> {
                e.setUsername(mapByUserIds.get(e.getCreatorId()));
            });

        return dataApiBaseDomains;
    }

    @Override
    public Long getTotalApiSumByProjectAndUserId(Long projectId, String userId) {

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, projectId)
                .eq(DataApiEntity::getCreatorId, userId);

        long count = this.count(eq);
        return count;
    }

    @Override
    public Long getTotalApiByProjectId(Long projectId) {
        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>().eq(DataApiEntity::getProjectId, projectId);
        long count = this.count(eq);
        return count;
    }

    @Override
    public Long getTotalPublishedApiByProjectId(Long projectId) {

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>().eq(DataApiEntity::getProjectId, projectId);
        List<DataApiEntity> multi = this.list(eq);
        multi.forEach(
            e -> {
                if (null == e.getTotalCount()) {
                    e.setTotalCount(0L);
                }
            });
        long sum =
            multi.stream().filter(Objects::nonNull).mapToLong(DataApiEntity::getTotalCount).sum();
        return sum;
    }

    @Override
    public Long getTotalFailApiByProjectId(Long projectId) {
        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>().eq(DataApiEntity::getProjectId, projectId);
        List<DataApiEntity> multi = this.list(eq);
        multi.forEach(
            e -> {
                if (null == e.getFailCount()) {
                    e.setFailCount(0L);
                }
            });
        long sum = multi.stream().filter(Objects::nonNull).mapToLong(DataApiEntity::getFailCount).sum();
        return sum;
    }

    @Override
    public List<DataApiDomain> getApiUsedTop(Long projectId, Integer reqStatus, String userId) {
        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>().eq(DataApiEntity::getProjectId, projectId);
        if (Objects.nonNull(userId)) {
            eq.eq(DataApiEntity::getCreatorId, userId);
        }
        // 0 - all 1-fail 2-sucess
        if (reqStatus == 0) {
            eq.gt(DataApiEntity::getTotalCount, 0);
            eq.orderByDesc(DataApiEntity::getTotalCount);
        } else if (reqStatus == 1) {
            eq.gt(DataApiEntity::getFailCount, 0);
            eq.orderByDesc(DataApiEntity::getFailCount);
        }
        //    eq.last("limit 10");

        List<DataApiEntity> dataApiEntities = this.list(eq);
        if (CollectionUtils.isNotEmpty(dataApiEntities) && dataApiEntities.size() > 10) {
            dataApiEntities = dataApiEntities.subList(0, 10);
        }
        List<DataApiDomain> dataApiDomains =
            ConvertUtil.copyProperties(dataApiEntities, DataApiDomain.class);

        return dataApiDomains;
    }

    @Override
    public Long testApi(DataApiBaseParam dataApiBaseParam, Long projectId) {

        DataApiTestParam dataApiTestParam = (DataApiTestParam) dataApiBaseParam;
        Map<String, String> param = Maps.newHashMap();
        List<DataApiParamParam> inputParamList = dataApiTestParam.getInputParamList();
        List<DataApiParamParam> outputParamList = dataApiTestParam.getOutputParamList();
        inputParamList.forEach(
            e -> {
                if (StringUtils.isNotBlank(e.getDefaultValue())) {
                    param.put(e.getParamName(), e.getDefaultValue());
                }
            });

        List<DataApiTaskParamDomain> allParamList = Lists.newArrayList();
        List<DataApiTaskParamDomain> dataApiInputDomainList =
            ConvertUtil.copyProperties(inputParamList, DataApiTaskParamDomain.class);
        if (CollectionUtils.isNotEmpty(dataApiInputDomainList)) {
            allParamList.addAll(dataApiInputDomainList);
        }
        List<DataApiTaskParamDomain> dataApiOutputDomainList =
            ConvertUtil.copyProperties(outputParamList, DataApiTaskParamDomain.class);
        if (CollectionUtils.isNotEmpty(dataApiOutputDomainList)) {
            allParamList.addAll(dataApiOutputDomainList);
        }

        DataApiDomain dataApiDomain = ConvertUtil.copyProperties(dataApiTestParam, DataApiDomain.class);
        dataApiDomain.setApiParamEntityList(allParamList);
        Long recordId = dataApiRestService.testDataApi(dataApiDomain, param);

        return recordId;
    }

    @Override
    public DataApiLogDomain getRequestTestLog(Long logId, Integer offset) {
        int start = 1;
        if (offset != null && !offset.equals(0)) {
            start = offset;
        }
        DataApiLogDomain response = new DataApiLogDomain();
        response.setLogEnd(true);
        response.setOffset(offset);
        response.setLogContent(Lists.newArrayList());
        try {
            String content = LogUtil.readDataApiResponse(logId);
            response.setResult(content);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }
        List<String> logs = Lists.newArrayList();
        try {
            logs = LogUtil.readDataApiTestLog(logId, start);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        if (CollectionUtils.isNotEmpty(logs)) {
            response.setOffset(logs.size() + start);
            response.setLogContent(logs);
        }

        return response;
    }

    @Override
    public DataApiLogDomain getRequestLog(Long logId, Integer offset) {
        int start = 1;
        if (offset != null && !offset.equals(0)) {
            start = offset;
        }
        DataApiLogDomain response = new DataApiLogDomain();
        response.setLogEnd(true);
        response.setOffset(offset);
        response.setLogContent(Lists.newArrayList());
        List<String> logs = Lists.newArrayList();
        try {
            logs = LogUtil.readDataApiLog(logId, start);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        }

        if (CollectionUtils.isNotEmpty(logs)) {
            response.setOffset(logs.size() + start);
            response.setLogContent(logs);
        }

        return response;
    }

    @Override
    public String getResponseExample(DataApiExampleTestParam dataApiGuideTestParam) {

        List<Map<String, Object>> list = Lists.newArrayList();

        Map<String, Object> item = new HashMap<>();
        List<DataApiParamParam> outputParams = dataApiGuideTestParam.getDataApiParamParams();
        for (DataApiParamParam dataApiParam : outputParams) {
            Object exampleValue = null;
            String paramDataType = dataApiParam.getParamDataType();
            if (StringUtils.equalsIgnoreCase("string", paramDataType)) {
                exampleValue = StringUtils.EMPTY;
            } else if (StringUtils.equalsIgnoreCase("boolean", paramDataType)) {
                exampleValue = true;
            } else {
                exampleValue = 0;
            }
            item.put(dataApiParam.getParamName(), exampleValue);
        }
        list.add(item);

        Integer pageable = dataApiGuideTestParam.getPageable();

        RestResponseEntity<Object> entity = new RestResponseEntity<>();

        if (null != pageable && pageable == 1) {
            PagedResult pagedResult = new PagedResult();
            pagedResult.setPageNum(1);
            pagedResult.setPageSize(10);
            pagedResult.setTotalElements(100L);
            pagedResult.setResult(list);
            pagedResult.setTotalPages(1);
            entity.setData(pagedResult);
        } else {
            entity.setData(list);
        }

        return JSON.toJSONString(entity);
    }

    @Override
    public Long testApi(Long apiId, HttpServletRequest request, Long projectId) {

        DataApiEntity dataApiEntity = this.getById(apiId);
        DataApiRegisterEntity dataApiRegister = dataApiEntity.getDataApiRegister();

        DataApiRegisterDomain convert = Convert.convert(DataApiRegisterDomain.class, dataApiRegister);
        Map<String, String> params = DataApiUtil.getParams(request);
        DataApiDomain dataApiDomain = Convert.convert(DataApiDomain.class, dataApiEntity);
        dataApiDomain.setApiRegisterDomain(convert);
        Long logId = dataApiRestService.testDataApi(dataApiDomain, params);
        return logId;
    }

    @Override
    public Long testApiAbacus(Long apiId, Map<String, String> params, Long projectId) {

        DataApiEntity dataApiEntity = this.getById(apiId);
        DataApiRegisterEntity dataApiRegister = dataApiEntity.getDataApiRegister();
        DataApiRegisterDomain convert = Convert.convert(DataApiRegisterDomain.class, dataApiRegister);
        DataApiDomain dataApiDomain = Convert.convert(DataApiDomain.class, dataApiEntity);
        dataApiDomain.setApiRegisterDomain(convert);
        Long logId = dataApiRestService.testDataApi(dataApiDomain, params);
        return logId;
    }

    @Override
    public void exportApi(List<Long> ids, String userId, Long projectId, HttpServletResponse response) {

        if (CollectionUtils.isEmpty(ids)) {
            throw new BusinessException("请选择api导出");
        }

        List<DataApiAuthEntity> dataApiAuthByIds =
            dataApiAuthService.getDataApiAuthByIds(ids, userId, projectId);

        Map<Long, DataApiAuthEntity> apiAuthEntityMap =
            dataApiAuthByIds.stream().collect(Collectors.toMap(e -> e.getApiId(), e -> e));

        List<DataApiEntity> dataApiEntities = this.listByIds(ids);
        List<DataApiExportInfoDomain> exportInfos = Lists.newArrayList();
        String fileName = null;
        for (DataApiEntity dataApiEntity : dataApiEntities) {

            DataApiExportInfoDomain exportInfo = new DataApiExportInfoDomain();
            List<DataApiExportInfoDomain.Param> reqParams = Lists.newArrayList();
            List<DataApiExportInfoDomain.Param> resParams = Lists.newArrayList();

            exportInfo.setName(dataApiEntity.getApiName());
            exportInfo.setDesc(dataApiEntity.getApiDesc());
            if (StringUtils.isNotBlank(dataApiEntity.getApiProtocol())) {
                if (dataApiEntity.getApiProtocol().equals("0")) {
                    exportInfo.setProtocol("http");
                } else {
                    exportInfo.setProtocol("https");
                }
            }
            exportInfo.setMethod(dataApiEntity.getApiMethod());
            String url = "未授权";

            Integer isSecurity = dataApiEntity.getIsSecurity();
            DataApiAuthEntity dataApiAuthEntity = apiAuthEntityMap.get(dataApiEntity.getId());
            if (null != dataApiAuthEntity) {
                String apiToken = dataApiAuthEntity.getApiToken();
                if (Objects.nonNull(dataApiEntity.getAuthType()) && dataApiEntity.getAuthType().equals(1)) {
                    UserDomain userDomain = userService.getUserById(userId);
                    apiToken = tokenService.getToken(userDomain.getId());
                }
                url = getApiFullPath(dataApiEntity.getApiPath(), apiToken, dataApiEntity.getAuthType(),
                    isSecurity);
            }
            exportInfo.setUrl(url);
            exportInfo.setResponseExample(dataApiEntity.getResponseExample());

            List<DataApiParamEntity> apiParamEntityList = dataApiEntity.getApiParamEntityList();
            if (CollectionUtils.isNotEmpty(apiParamEntityList)) {
                for (DataApiParamEntity dataApiParamEntity : apiParamEntityList) {
                    DataApiExportInfoDomain.Param param = new DataApiExportInfoDomain.Param();
                    param.setName(dataApiParamEntity.getParamName());
                    if (StringUtils.isBlank(dataApiParamEntity.getParamName())) {
                        param.setName(dataApiParamEntity.getBindColumnName());
                    }

                    param.setDataType(dataApiParamEntity.getParamDataType());
                    param.setRequired(
                        (dataApiParamEntity.getParamRequire() == null
                            || dataApiParamEntity.getParamRequire() == 0)
                            ? "否"
                            : "是");
                    param.setDesc(dataApiParamEntity.getParamDesc());
                    Integer paramType = dataApiParamEntity.getParamType();
                    if (paramType == 0) {
                        reqParams.add(param);
                    } else {
                        param.setRequired("否");
                        resParams.add(param);
                    }
                }
            }
            Integer pageable = dataApiEntity.getPageable();
            if (Objects.nonNull(pageable) && pageable.equals(1)) {
                DataApiExportInfoDomain.Param pageSizeParam = new DataApiExportInfoDomain.Param();
                pageSizeParam.setName(DataApiCommomParam.PAGESIZE);
                pageSizeParam.setRequired("否");
                pageSizeParam.setDataType("INT");
                pageSizeParam.setDesc("每页大小");

                DataApiExportInfoDomain.Param pageNumParam = new DataApiExportInfoDomain.Param();
                pageNumParam.setName(DataApiCommomParam.PAGENUM);
                pageNumParam.setRequired("否");
                pageNumParam.setDataType("INT");
                pageNumParam.setDesc("第几页");

                reqParams.add(pageSizeParam);
                reqParams.add(pageNumParam);
            }
            exportInfo.setReqParams(reqParams);
            exportInfo.setResParams(resParams);
            exportInfos.add(exportInfo);
            fileName = String.format("data-engine-api-%s.doc", dataApiEntity.getApiName());
        }
        Map<String, Object> map = new HashMap<>();
        map.put("apiList", exportInfos);

        if (ids.size() > 1) {
            fileName = "data-engine-api.doc";
        }
        try {
            exportWord(fileName, map, response);
        } catch (Exception ex) {
            log.error("文档生成失败", ex);
            throw new BusinessException("文档生成失败");
        }
    }

    @Override
    public List<DataApiTaskParamDomain> getParams(String sql, Long dsId) {

        List<SQLSelectItem> sqlSelectItems =
            DataApiUtil.getSqlSelectItemsBySql(sql, String.valueOf(JdbcConstants.MYSQL));

        List<DataApiTaskParamDomain> rs1 = Lists.newArrayList();
        if (CollectionUtils.isEmpty(sqlSelectItems)) {
            return rs1;
        }

        sqlSelectItems.forEach(
            x -> {
                String alias = x.getAlias();
                String column = x.getExpr().toString();
                if (column.contains(" ")) {
                    column = column.substring(0, column.indexOf(" "));
                }
                if (StringUtils.equals("*", column)) {
                    return;
                }

                if (StringUtils.isBlank(alias)) {
                    alias = column;
                }
                if (alias.contains(".")) {
                    alias = alias.substring(alias.indexOf(".") + 1);
                }
                DataApiTaskParamDomain dataApiTaskParamDomain = new DataApiTaskParamDomain();
                dataApiTaskParamDomain.setParamName(alias);
                dataApiTaskParamDomain.setBindColumnName(column);
                dataApiTaskParamDomain.setParamType(1);
                rs1.add(dataApiTaskParamDomain);
            });

        String regex = "([^\\\\])\\$\\{\\s*([a-zA-Z0-9_-]+)\\s*\\}";
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(sql);

        while (matcher.find()) {
            DataApiTaskParamDomain dataApiTaskParamDomain = new DataApiTaskParamDomain();
            dataApiTaskParamDomain.setParamName(matcher.group(2));
            dataApiTaskParamDomain.setBindColumnName(null);
            dataApiTaskParamDomain.setParamType(0);
            rs1.add(dataApiTaskParamDomain);
        }

        if (dsId != null && CollectionUtils.isNotEmpty(rs1)) {
            DataSourceDetailDomain dataSourceDetail =
                dataSourceService.getDataSourceDetailById(dsId, true);
            // 用户指定了select的列，如果是InfluxDB数据源，且存在下列下种情况，返回结果需要进行调整：
            // 1. 用户没有指定time列，需要额外在返回列表的开始新增time信息
            // 2. 用户指定了time列，但是time列不在列表的第一个位置，需要将time列调整到队列开始位置
            if (dataSourceDetail != null && DSType.InfluxDB.name().equals(dataSourceDetail.getDsType())) {
                boolean hasTimeColumn = false;
                for (DataApiTaskParamDomain param : rs1) {
                    if (StringUtils.equalsIgnoreCase("time", param.getParamName())) {
                        hasTimeColumn = true;
                        break;
                    }
                }
                if (!hasTimeColumn) {
                    DataApiTaskParamDomain timeParam = new DataApiTaskParamDomain();
                    timeParam.setParamName("time");
                    timeParam.setBindColumnName("time");
                    timeParam.setParamType(1);
                    rs1.add(0, timeParam);
                } else {
                    for (int i = 0; i < rs1.size(); i++) {
                        DataApiTaskParamDomain param = rs1.get(i);
                        if (StringUtils.equalsIgnoreCase("time", param.getParamName())) {
                            if (i != 0) {
                                rs1.remove(i);
                                rs1.add(0, param);
                            }
                            break;
                        }
                    }
                }
            }
        }

        return rs1;
    }

    @Override
    public List<DataApiTaskParamDomain> getTestInfo(Long apiId) {
        DataApiEntity dataApiEntity = this.getById(apiId);
        Integer apiType = dataApiEntity.getApiType();
        if (DataApiTaskTypeEnum.GUIDE.getTypeCode().equals(apiType)
            || DataApiTaskTypeEnum.SCRIPT.getTypeCode().equals(apiType)
            || DataApiTaskTypeEnum.INDEXLIB.getTypeCode().equals(apiType)) {
            List<DataApiParamEntity> apiParamEntityList = dataApiEntity.getApiParamEntityList();
            List<DataApiTaskParamDomain> dataApiTaskParamDomains =
                ConvertUtil.copyProperties(apiParamEntityList, DataApiTaskParamDomain.class);
            List<DataApiTaskParamDomain> r1 =
                dataApiTaskParamDomains.stream()
                    .filter(e -> e.getParamType().equals(0))
                    .map(
                        e -> {
                            if (StringUtils.isBlank(e.getParamName())) {
                                e.setParamName(e.getBindColumnName());
                            }
                            return e;
                        })
                    .collect(Collectors.toList());
            Integer pageable = dataApiEntity.getPageable();
            if (Objects.equals(pageable, 1)) {
                DataApiTaskParamDomain paramPageNum = new DataApiTaskParamDomain();
                paramPageNum.setParamType(0);
                paramPageNum.setDefaultValue("1");
                paramPageNum.setParamRequire(0);
                paramPageNum.setParamName("pageNum");
                paramPageNum.setParamDataType("INT");
                r1.add(paramPageNum);

                DataApiTaskParamDomain paramPageSize = new DataApiTaskParamDomain();
                paramPageSize.setParamType(0);
                paramPageSize.setDefaultValue("10");
                paramPageSize.setParamRequire(0);
                paramPageSize.setParamName("pageSize");
                paramPageSize.setParamDataType("INT");
                r1.add(paramPageSize);
            }
            return r1;
        }
        return null;
    }

    /**
     * @param projectId
     * @param indexId
     * @description : 找到跟指标关联的数据服务
     * @author : tinglan.ys
     * @date : 2022/5/13
     */
    @Override
    public List<DataApiEntity> findByProjectIdIndexId(Long projectId, Long indexId) {

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getProjectId, projectId)
                .eq(DataApiEntity::getApiType, DataApiTaskTypeEnum.INDEXLIB.getTypeCode());

        List<DataApiEntity> dataApiEntities = this.list(eq);
        List<DataApiEntity> collect =
            dataApiEntities.stream()
                .filter(
                    e -> {
                        DataApiIndexEntity dataApiIndex = e.getDataApiIndex();
                        if (Objects.isNull(dataApiIndex)) {
                            return false;
                        }
                        if (Objects.equals(dataApiIndex.getIndexId(), indexId)) {
                            return true;
                        }
                        return false;
                    })
                .collect(Collectors.toList());
        return collect;
    }

    //    @BizDataIndexAnnotation(
//        type = BizDataIndexTypeEnum.DATA_SERVICE,
//        dataIdFieldName = "id",
//        dataIdParamIndex = 0,
//        operateType = OperateType.DELETE)
    @Override
    public Boolean deleteDir(Long id) {

        List<DirectoryEntity> childrenById =
            directoryService.getChildrenById(
                id, ServletUtils.getProjectId(), DirectoryMenuEnum.OFFLINE);
        List<Long> ids = childrenById.stream().map(DirectoryEntity::getId).collect(Collectors.toList());
        ids.add(id);

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .in(DataApiEntity::getApiGroupId, ids)
                .eq(DataApiEntity::getProjectId, ServletUtils.getProjectId());

        long count = this.count(eq);
        if (count > 0) {
            throw new BusinessException("该目录下存在任务，无法删除");
        }
        directoryService.deleteDir(id, DirectoryMenuEnum.OFFLINE);
        return Boolean.TRUE;
    }

    @Override
    public Long testRegisterApi(DataApiRegisterParam dataApiRegisterParam) {

        DataApiRegisterDomain dataApiRegisterDomain =
            Convert.convert(DataApiRegisterDomain.class, dataApiRegisterParam);
        DataApiDomain dataApiDomain = new DataApiDomain();
        dataApiDomain.setApiType(DataApiTaskTypeEnum.REGIEST.getTypeCode());
        dataApiDomain.setApiRegisterDomain(dataApiRegisterDomain);
        Map<String, String> param = Maps.newHashMap();
        Long logId = dataApiRestService.testDataApi(dataApiDomain, param);
        return logId;
    }

    private void exportWord(String fileName, Map<String, Object> map, HttpServletResponse response)
        throws IOException, TemplateException {
        Configuration configure = new Configuration(new Version("2.3.28"));
        configure.setDefaultEncoding("UTF-8");
        configure.setClassForTemplateLoading(this.getClass(), "/templates/");
        String fileNameURL = URLEncoder.encode(fileName, "UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileNameURL);
        response.setContentType("application/octet-stream");
        response.setHeader("content-type", "application/octet-stream");

        Template template = configure.getTemplate("data_api_template.ftl", "UTF-8");

        File tempFile = new File(FileUtils.getTempDirectoryPath() + File.separator + fileNameURL);

        try (Writer w = new OutputStreamWriter(new FileOutputStream(tempFile), "utf-8")) {

            template.process(map, w);

            FileUtils.copyFile(tempFile, response.getOutputStream());

            FileUtils.deleteQuietly(tempFile);
        }
    }

    private String getApiFullPath(String apiPath, String apiToken, Integer apiAuthType,
                                  Integer isSecurity) {
        StringBuilder sb = new StringBuilder();

        if (Objects.nonNull(isSecurity) && isSecurity.equals(1)) {
            String dataApiKey = dataApiConfig.getDataApiKey();
            String dataApiSecretType = dataApiConfig.getDataApiSecretType();
            apiToken = AESUtil.encrypt(apiToken, dataApiKey, dataApiSecretType);
        }

        String dataApiUriPrefix = dataApiConfig.getDataApiUriPrefix();

        if (StringUtils.isNotBlank(dataApiUriPrefix)) {
            sb.append(dataApiUriPrefix);
            if (dataApiUriPrefix.endsWith("/")) {
                sb.deleteCharAt(sb.length() - 1);
            }
        }
        String contextPath = ServletUtils.getRequest().getContextPath();
        if (!StringUtils.contains(dataApiUriPrefix, contextPath)) {
            sb.append(contextPath);
        }
        if (!StringUtils.contains(dataApiUriPrefix, SERVLETPATH)) {
            sb.append(SERVLETPATH);
        }

        sb.append(apiPath);
        if (Objects.nonNull(apiAuthType) && apiAuthType.equals(1)) {
            sb.append("?userToken=");
        } else {
            sb.append("?apiToken=");
        }
        sb.append(apiToken);

        return sb.toString();
    }

    private String getTestApiToken(Long apiId, Integer authType, String apiPath, Integer isSecurity) {
        String key = dataApiRedisKeyPrefix + "test_token_" + apiId;
        String token = redisTemplate.opsForValue().get(key);

        if (StringUtils.isBlank(token)) {
            token = UUID.randomUUID().toString().replaceAll("-", "");
            redisTemplate.opsForValue().set(key, token, 3, TimeUnit.MINUTES);
            String tokenKey = dataApiRedisKeyPrefix + "test_token_" + token + apiPath;
            DataApiTokenDomain tokenDomain = new DataApiTokenDomain();
            tokenDomain.setApiId(apiId);
            tokenDomain.setIsProd(false);
            tokenDomain.setIsSecurity(isSecurity);

            redisTemplate
                .opsForValue()
                .set(tokenKey, JSON.toJSONString(tokenDomain), 3, TimeUnit.MINUTES);
        }

        return token;
    }

    @Override
    public List<DataApiConfigInfoDomain> getDataApiConfigs(Integer total) {

        LambdaQueryWrapper<DataApiEntity> eq =
            new LambdaQueryWrapper<DataApiEntity>()
                .eq(DataApiEntity::getApiStatus, DataApiStatusEnum.PUBLISHED.getStatus());
        eq.last("limit " + total);
        List<DataApiEntity> dataApiEntities = this.list(eq);

        List<DataApiConfigInfoDomain> dataApiConfigInfoDomains = Lists.newArrayList();

        for (DataApiEntity dataApiEntity : dataApiEntities) {
            try {
                DataApiConfigInfoDomain dataApiConfig = this.getDataApiConfig(dataApiEntity.getId());
                if (Objects.nonNull(dataApiConfig)) {
                    dataApiConfigInfoDomains.add(dataApiConfig);
                }
            } catch (RuntimeException e) {
                log.error(e.getMessage());
            }
        }

        return dataApiConfigInfoDomains;
    }

    @Override
    public List<DataApiEntity> getListByPage(Long projectId, Integer pageSize, Integer pageNum) {
        Page<DataApiEntity> r1 =
            page(
                new Page<>(pageNum, pageSize),
                new LambdaQueryWrapper<DataApiEntity>().eq(DataApiEntity::getProjectId, projectId));
        return r1.getRecords();
    }

    @Override
    @Transactional
    public boolean resetUserToken(String password) {
        String userId = UserContext.getUserId();
//        UserDomain userEntity = userService.getUserById(userId);
//        if (!userEntity.getPassword().equalsIgnoreCase(password)) {
//            throw new BusinessException("密码错误");
//        }

        // TODO: 重置时更新到token表
//        String s = UUID.randomUUID().toString().replaceAll("-", "");
//        userEntity.setUserToken(s);
//        userService.updateById(userEntity);
        tokenService.resetToken(userId);

        // 刷新redis api信息
        dataApiAuthService.initProdApiToRedis();

        return false;
    }

    @Override
    public List<String> getNodeTableById(Long jobId) {
        DataApiEntity byId = this.getById(jobId);
        Integer apiType = byId.getApiType();
        List<String> res = Lists.newArrayList();
        DataSourceDetailDomain dataSourceDetailById = dataSourceService.getDataSourceDetailById(
            byId.getDatasourceId(), false);
        if (!dataSourceDetailById.getIsSystem().equals(1)) {
            return Lists.newArrayList();
        }
        if (DataApiTaskTypeEnum.GUIDE.getTypeCode().equals(apiType)) {
            res.add(byId.getTableName());
        } else if (DataApiTaskTypeEnum.SCRIPT.getTypeCode().equals(apiType)) {
            Map<String, List<String>> stringListMap = this.secretMgtService.parserSQLSecurity(
                byId.getApiScript());
            List<String> strings = stringListMap.get("other");
            res.addAll(strings);
        }
        return res;
    }
}
